package com.lancoo.ccas53.service.impl;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lancoo.ccas53.entity.Holiday;
import com.lancoo.ccas53.entity.TaskInfo;
import com.lancoo.ccas53.exception.BizException;
import com.lancoo.ccas53.mapper.HolidayMapper;
import com.lancoo.ccas53.pojo.response.HolidayResponse;
import com.lancoo.ccas53.service.HolidayService;
import com.lancoo.ccas53.service.TaskInfoService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 节假日安排 服务实现类
 * </p>
 *
 * @author quin.song
 * @since 2024-05-20
 */
@Service
public class HolidayServiceImpl extends ServiceImpl<HolidayMapper, Holiday> implements HolidayService {

    @Resource
    private TaskInfoService taskInfoService;


    @Override
    public List<Holiday> syncHoliday(Integer taskId) {
        // http://timor.tech/api/holiday  调用接口获取节假日信息
        String url = "http://timor.tech/api/holiday/year/";
        //获取任务起止时间
        TaskInfo taskInfo = taskInfoService.getById(taskId);
        //任务存在跨年 拿到起止日期的两个年份
        Integer startYear = taskInfo.getTermBeginTime().getYear();
        Integer endYear = taskInfo.getTermEndTime().getYear();

        LinkedHashMap<String, Object> holidayMap = null;
        try {
            String startString = HttpUtil.createGet(url + startYear).execute().body();
            HolidayResponse startYearHolidayResponse = JSONObject.parseObject(startString, HolidayResponse.class);
            holidayMap = startYearHolidayResponse.getHoliday();
        } catch (HttpException e) {
            throw new BizException("调用节假日接口失败");
        }

        //遍历节假日信息 并入库
        List<Holiday> holidayList = new ArrayList<>();
        for (Map.Entry<String, Object> entry : holidayMap.entrySet()) {
            Map<String, Object> mapValue = (Map<String, Object>) entry.getValue();
            Boolean holiday = (Boolean) mapValue.get("holiday");
            String name = (String) mapValue.get("name");
            String date = mapValue.get("date").toString();

            //过滤学期内的节假日
            LocalDate holidayDate = LocalDate.parse(date);
            if (holidayDate.isBefore(taskInfo.getTermBeginTime().toLocalDate())
                    || holidayDate.isAfter(taskInfo.getTermEndTime().toLocalDate())) {
                continue;
            }

            holidayList.add(new Holiday()
                    .setTaskId(taskId)
                    .setHolidayDate(holidayDate)
                    .setHolidayName(name)
                    .setFlag(holiday ? 1 : 2));
        }

        LinkedHashMap<String, Object> holidayMapNext = new LinkedHashMap<>();
        if (!startYear.equals(endYear)) {
            String endString = HttpUtil.createGet(url + endYear).execute().body();
            HolidayResponse endYearHolidayResponse = JSONObject.parseObject(endString, HolidayResponse.class);
            //学期不会超过一年 key不会重复的
            holidayMapNext = endYearHolidayResponse.getHoliday();
        }
        for (Map.Entry<String, Object> entry : holidayMapNext.entrySet()) {
            Map<String, Object> mapValue = (Map<String, Object>) entry.getValue();
            Boolean holiday = (Boolean) mapValue.get("holiday");
            String name = (String) mapValue.get("name");
            String date = mapValue.get("date").toString();

            //过滤学期内的节假日
            LocalDate holidayDate = LocalDate.parse(date);
            if (holidayDate.isBefore(taskInfo.getTermBeginTime().toLocalDate())
                    || holidayDate.isAfter(taskInfo.getTermEndTime().toLocalDate())) {
                continue;
            }

            holidayList.add(new Holiday()
                    .setTaskId(taskId)
                    .setHolidayDate(holidayDate)
                    .setHolidayName(name)
                    .setFlag(holiday ? 1 : 2));
        }

        //批量插入
        List<Holiday> existHoliday = this.lambdaQuery().eq(Holiday::getTaskId, taskId).list();
        holidayList.removeAll(existHoliday);
        this.saveBatch(holidayList);
        return holidayList;
    }

}
